package com.scujj.cs6.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scujj.cs6.model.entity.IprangeInfo;
import com.scujj.cs6.service.IprangeInfoService;
import com.scujj.cs6.mapper.IprangeInfoMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import static com.scujj.cs6.utils.RequestUtils.getIpAddr;

/**
* @author FlanChan
* @description 针对表【iprange_info】的数据库操作Service实现
* @createDate 2025-04-07 11:32:42
*/
@Service
public class IprangeInfoServiceImpl extends ServiceImpl<IprangeInfoMapper, IprangeInfo>
    implements IprangeInfoService{

    @Override
    public IprangeInfo getLocation(HttpServletRequest request) {
        String ipAddr = getIpAddr(request);
        IprangeInfo location = this.baseMapper.selectLocation(ipAddr);
        return location != null ? location : this.baseMapper.selectLocation(getExternalIp());
    }


    /**
     * 获取外网ip
     * @return {@link String}
     */
    private String getExternalIp() {
        String ip = null;
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet("http://checkip.amazonaws.com");
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                ip = EntityUtils.toString(response.getEntity()).trim();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }
}




